package com.qingke.example;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ValidateServlet
 */
@WebServlet("/ValidateServlet")
public class ValidateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private final String driver="com.mysql.jdbc.Driver";
	private final String url="jdbc:mysql://localhost:3306/web?useSSL=false";
	private final String u="root";
	private final String p="6775";

	private Connection conn = null;
	private String sql;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
       
    public ValidateServlet() {
        super();
    }

	public void init(ServletConfig config) throws ServletException {
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, u, p);
			System.out.println("Connect to database successfully!");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String username =request.getParameter("username");
		String password=request.getParameter("password");
		sql="select * from user where username=? and password=? ";
		
		try {
			ps=conn.prepareStatement(sql);
			ps.setString(1, username);
			ps.setString(2, password);
			rs=ps.executeQuery();
			if(rs.next()){
				request.getSession().setAttribute("username", username);
				request.getSession().setAttribute("password", password);
				request.getSession().setAttribute("logged",new Integer(1));
				response.sendRedirect("LoginServlet?username="+username);
				
			}else{	
				throw  new  NullPointerException("null pointer");
			}						
		} catch (SQLException e) {
			e.printStackTrace();
			throw  new  NullPointerException("null pointer");
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
